//
//  ALPS_MainController.m
//  Alps
//
//  Created by dllo on 16/6/6.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ALPS_MainController.h"
#import "ALPS_MainTableViewCell.h"
#import "WSSNetTool.h"
#import "ALPS_MainModel.h"
#import "ALPS_CarouselFigureTool.h"
#import "ALPS_FocusModel.h"
#import "ALPS_DiscoveryCollectionViewCell.h"
#import "ALPS_ColumnTableViewCell.h"
#import "ALPS_MainMoreViewController.h"
#import "ALPS_RecommendViewController.h"
#import "ALPS_ListenViewController.h"
#import "ALPS_ClassifyClickClickAlbumController.h"
#import "ALPS_SpecialIntroViewController.h"
#import "ALPS_PlayerMainViewController.h"
#import "ALPS_CollectViewController.h"
#import "ALPS_SpecialDetailModel.h"

@interface ALPS_MainController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource>
/** 主界面 */
@property (nonatomic, strong) UITableView *tableView;
/** 数据源数组 */
@property (nonatomic, strong) NSMutableArray *dataSource;
/** 是否存在头视图 */
@property (nonatomic, assign) BOOL hasHeaderView;
/** 轮播图数组 */
@property (nonatomic, strong) NSMutableArray *focusArray;
/** 头视图 */
@property (nonatomic, strong) UIView *headerView;
/** 头视图按钮数组 */
@property (nonatomic, strong) NSMutableArray *discoveryArray;
/** 页码 */
@property (nonatomic, assign) NSInteger pageNum;
/** 播放页数组 */
@property (nonatomic, strong) NSMutableArray *trackIdArr;
@end

@implementation ALPS_MainController

- (void)dealloc
{
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setMainTableView];
    [self getDataByURL];
    [self AddAlpsTitle];
    [self defaultCenterPushCollectVC];
}

- (void)AddAlpsTitle
{
    UIImageView *titleImgView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreeWidth*0.3, -5, ScreeWidth*0.4 ,55)];
    titleImgView.image = [UIImage imageNamed:@"ALPS_Title 2"];
    [self.view addSubview:titleImgView];
}

#pragma mark -- 主界面
- (void)setMainTableView
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreeWidth, ScreeHeight - 99) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource =self;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    
    [self.tableView registerClass:[ALPS_MainTableViewCell class] forCellReuseIdentifier:@"mainCell"];
    
    [self.tableView registerClass:[ALPS_ColumnTableViewCell class] forCellReuseIdentifier:@"columnCell"];
    
    //设置头视图
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreeWidth, ScreeHeight / 5 * 2)];
    self.tableView.tableHeaderView = self.headerView;
    
    //下拉刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self reloadData];
    }];
    [header setTitle:@"下拉可以刷新..." forState:MJRefreshStateIdle];
    [header setTitle:@"松开即可刷新" forState:MJRefreshStatePulling];
    [header setTitle:@"玩命加载中..." forState:MJRefreshStateRefreshing];
    self.tableView.mj_header = header;
    
}

#pragma mark -- 解析数据
- (void)getDataByURL
{
    [WSSNetTool GetNetByURL:@"http://mobile.ximalaya.com/mobile/discovery/v2/recommends?channel=and-d10&device=android&includeActivity=true&includeSpecial=true&scale=2&statEvent=pageview%2Ftab%40发现_推荐&version=4.3.92" body:nil headers:nil response:WSSJSON success:^(id result) {
        self.dataSource = [NSMutableArray array];
        self.focusArray = [NSMutableArray array];
        self.trackIdArr = [NSMutableArray array];
        self.discoveryArray = [NSMutableArray array];
        //------------------------------头视图----------------------------------//
        //轮播图
        NSDictionary *focusDic = [result objectForKey:@"focusImages"];
        NSArray *focusArr = [focusDic objectForKey:@"list"];
        for (NSDictionary *dic in focusArr) {
            ALPS_FocusModel *model = [[ALPS_FocusModel alloc] initWithDic:dic];
            ALPS_SpecialDetailModel *spModel = [[ALPS_SpecialDetailModel alloc] initWithDic:dic];
            if (model.type == 2 || model.type == 3 || model.type == 9) {
                [self.focusArray addObject:model];
                [self.trackIdArr addObject:spModel];
            }
        }
        NSDictionary *discoveryDic = [result objectForKey:@"discoveryColumns"];
        NSArray *discoveryArr = [discoveryDic objectForKey:@"list"];
        for (NSDictionary *dic in discoveryArr) {
            ALPS_MainModel *model = [[ALPS_MainModel alloc] initWithDic:dic];
            [self.discoveryArray addObject:model];
        }
        if (self.hasHeaderView == NO) {
            //轮播图
            ALPS_CarouselFigureTool *tool = [ALPS_CarouselFigureTool direcWithtFrame:CGRectMake(0, 0, ScreeWidth, ScreeHeight / 4) ImageArr:self.focusArray AndImageClickBlock:^(NSInteger index) {
                ALPS_FocusModel *model = [self.focusArray objectAtIndex:index];
                switch (model.type) {
                    case 9:{
                        ALPS_SpecialIntroViewController *SIVC = [[ALPS_SpecialIntroViewController alloc] init];
                        SIVC.specialId = model.specialId;
                        [self.navigationController pushViewController:SIVC animated:YES];
                    }
                        break;
                    case 2:{
                        ALPS_ClassifyClickClickAlbumController *CCCAC = [[ALPS_ClassifyClickClickAlbumController alloc] init];
                        CCCAC.albumId = model.albumId;
                        [self.navigationController pushViewController:CCCAC animated:YES];
                    }
                        break;
                    case 3:{
                        ALPS_PlayerMainViewController *PMVC = [[ALPS_PlayerMainViewController alloc] init];
                        PMVC.trackId = model.trackId;
                        PMVC.listArr = self.trackIdArr;
                        [self.navigationController pushViewController:PMVC animated:YES];
                    }
                        break;
                    default:
                        break;
                }
            }];
            [self.headerView addSubview:tool];
            //按钮
            UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
            flowLayout.itemSize = CGSizeMake(ScreeWidth / 4.5, ScreeHeight / 20 * 3 - 10);
            flowLayout.minimumLineSpacing = 0;
            flowLayout.minimumInteritemSpacing = 0;
            flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
            flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
            
            UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, ScreeHeight / 4, ScreeWidth, ScreeHeight / 20 * 3 - 10) collectionViewLayout:flowLayout];
            collectionView.backgroundColor = [UIColor whiteColor];
            collectionView.delegate = self;
            collectionView.dataSource = self;
            collectionView.showsHorizontalScrollIndicator = NO;
            [self.headerView addSubview:collectionView];
            
            [collectionView registerClass:[ALPS_DiscoveryCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
            
            //分割线
            UILabel *lineLabel = [[UILabel alloc] init];
            lineLabel.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
            [self.headerView addSubview:lineLabel];
            [lineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_offset(UIEdgeInsetsMake(ScreeHeight / 5 * 2 - 10, 0, 0, 0));
            }];
            self.hasHeaderView = YES;
        }
        
        //-------------------------小编推荐~精品听单~热门推荐-------------------------//
        //小编推荐
        NSDictionary *dic = [result objectForKey:@"editorRecommendAlbums"];
        ALPS_MainModel *model = [[ALPS_MainModel alloc] initWithDic:dic];
        [self.dataSource addObject:model];
        
        //精品听单
        NSDictionary *columnDic = [result objectForKey:@"specialColumn"];
        ALPS_MainModel *columnModel = [[ALPS_MainModel alloc] initWithDic:columnDic];
        [self.dataSource addObject:columnModel];
        
        //热门推荐
        NSDictionary *hotDic = [result objectForKey:@"hotRecommends"];
        NSArray *hotArr = [hotDic objectForKey:@"list"];
        for (NSDictionary *dict in hotArr) {
            ALPS_MainModel *model = [[ALPS_MainModel alloc] initWithDic:dict];
                [self.dataSource addObject:model];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return ScreeHeight / 2.668 + 10;
    } else {
    return ScreeHeight / 2.668;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ALPS_MainModel *model = [self.dataSource objectAtIndex:indexPath.section];
    __weak ALPS_MainController *MC = self;
    if (indexPath.section == 1) {
        ALPS_ColumnTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"columnCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        
        //页面跳转
        cell.block = ^(NSInteger number)
        {
            ALPS_SpecialIntroViewController *siVC = [[ALPS_SpecialIntroViewController alloc] init];
            siVC.specialId = number;
            [MC.navigationController pushViewController:siVC animated:YES];
        };
        return cell;
    } else {
        ALPS_MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mainCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        
        //页面跳转
        cell.block = ^(NSInteger number)
        {
            ALPS_ClassifyClickClickAlbumController *CCCAC = [[ALPS_ClassifyClickClickAlbumController alloc] init];
            [MC.navigationController pushViewController:CCCAC animated:YES];
            CCCAC.albumId = number;
        };
        return cell;
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.discoveryArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ALPS_DiscoveryCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    ALPS_MainModel *model = [self.discoveryArray objectAtIndex:indexPath.row];
    cell.model = model;
    return cell;
}

- (void)reloadData
{
    [self.dataSource removeAllObjects];
    [self.focusArray removeAllObjects];
    [self getDataByURL];
    [self.tableView reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        ALPS_RecommendViewController *RVC = [[ALPS_RecommendViewController alloc] init];
        [self.navigationController pushViewController:RVC animated:YES];
    } else if (indexPath.section == 1){
        ALPS_ListenViewController *LVC = [[ALPS_ListenViewController alloc] init];
        [self.navigationController pushViewController:LVC animated:YES];
    } else {
        ALPS_MainMoreViewController *MMVC = [[ALPS_MainMoreViewController alloc] init];
        MMVC.navigationItemTitle = [[self.dataSource objectAtIndex:indexPath.section] title];
        NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"推荐", nil];
        MMVC.dataSource = array;
        MMVC.categoryId = [[self.dataSource objectAtIndex:indexPath.section] categoryId];
        [self.navigationController pushViewController:MMVC animated:YES];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld", indexPath.row);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
